const rewire = require("rewire")
const R = require('ramda')
const utils = rewire('../common/utils.cjs')
const fetch = rewire('../common/fetch.cjs')
const {getLogger} = rewire('../common/logger.cjs')
const logger = getLogger('file')

async function downloadFile(url, path) {
    logger.info('正在下载：' + url)
    const dir = R.dropLast(1, path.split('/')).join('/')
    if (!existDir(dir)) {
        makeDir(dir)
    }
    const buff = await download(url)
    fs.writeFileSync(path, buff, 'binary')
}


const fetcher = fetch.withConfig(fetch.makeFetcher(), {responseType: 'arraybuffer'})

async function download(url) {
    try {
        const resp = await fetcher(url)
        return resp.data
    } catch (e) {
        logger.error(e.message)
        logger.error('图片获取失败' + url)
    }
}

function uploadFile(buff, key, cos, bucket = '', region = '', storageType='STANDARD') {
    return new Promise(function (success, fail) {
        cos.putObject({
            Bucket: bucket,
            Region: region,
            Key: key,
            Body: buff,
            StorageClass: storageType
        }, function (err, data) {
            if (err) {
                fail(err)
            }
            else {
                success(key)
            }
        })
    })
}

/**
 * 
 * @param {*} url 待下载的文件地址
 * @param {*} basePath base路径
 * @param {*} cos 
 * @param {*} bucket 
 * @param {*} region 
 * @returns 返回
 */
async function downloadAndUpload(url, basePath, cos, bucket = '', region = '', storageType='STANDARD') {
    const buff = await download(url)
    const pies = url.split('.')
    const suffix = '.png'
    if (R.length(pies) > 1) {
        suffix = '.' + R.last(pies)
    }
    const key = basePath + '/' + utils.uuid() + suffix
    await uploadFile(buff, key, cos, bucket, region, storageType)
    return key
}

module.exports = { downloadFile, downloadAndUpload }